<template>
    <div class="uploadBox">
        <!-- 返回主页 -->
        <div class="homeBox">
            <router-link to="/">
                <el-tooltip content="返回列表页面" placement="top">
                    <i class="el-icon-tickets"></i>
                </el-tooltip>
            </router-link>
        </div>

        <!-- 上传文件按钮 -->
        <div class="buttonBox">
            <el-upload action accept=".xlsx,.xls" :auto-upload="false" :show-file-list="false" :on-change="handle">
                <el-button type="primary" slot="trigger">选取 Excel 文件</el-button>
            </el-upload>
            <el-button type="success" @click="submit" :disabled="disabled">采集数据提交</el-button>
        </div>

        <!-- 解析出来的数据 -->
        <div class="tableBox" v-show="show">
            <h3>
                <i class="el-icon-info"> 小主，以下是采集完成的数据，请您检查无误后，点击“采集数据提交”按钮上传至服务器</i>
            </h3>
            <el-table :data="tempData" border style="width: 100%" :height="height">
                <el-table-column prop="name" label="姓名" min-width="50%"></el-table-column>
                <el-table-column prop="phone" label="电话" min-width="50%"></el-table-column>
            </el-table>
        </div>
    </div>
</template>

<script>
import xlsx from 'xlsx';
import { Loading } from 'element-ui';
import { readFile, character, delay } from '@/utils';
import { createAPI } from '@/api';
export default {
    name: 'Upload',
    data() {
        return {
            height: document.documentElement.clientHeight - 130,
            tempData: [],
            show: false,
            disabled: false
        };
    },
    methods: {
        async handle(file) {
            const raw = file.raw;
            if (!raw) return;

            // 每次上传把之前的结果都藏起来了
            this.show = false;

            // 提示是异步的
            const loading = Loading.service({
                text: '小主，请您稍等片刻，女家正在玩命处理中...',
                background: 'rgba(0,0,0,.5)'
            });

            // !得到二进制
            const data = await readFile(raw);

            // !通过 xlsx 读取成普通数据
            // const workbook = xlsx.read(data, { type: 'binary' });
            const workbook = xlsx.read(data, { type: 'array' });
            const worksheet = workbook.Sheets[workbook.SheetNames[0]];
            const list = xlsx.utils.sheet_to_json(worksheet);

            // 把读取出来的数据变为可以提交为服务器的数据格式
            const arr = [];
            // #1 const oldData = JSON.parse(window.localStorage.getItem('excel') || '[]');
            // #2 let index = oldData.length;
            list.forEach((item) => {
                const obj = {};
                for (let key in character) {
                    if (!character.hasOwnProperty(key)) break;
                    // key => name、phone
                    let v = character[key],
                        text = v.text, // 姓名、电话
                        type = v.type;
                    v = item[text] || ''; // “真值”
                    type === 'string' ? (v = String(v)) : null;
                    type === 'number' ? (v = Number(v)) : null;
                    obj[key] = v;
                }
                // #3 obj.id = ++index;
                // #4 obj.time = new Date();
                arr.push(obj);
            });

            await delay(3000);

            this.show = true;
            this.tempData = arr;
            loading.close();
        },
        submit() {
            if (this.tempData.length <= 0) {
                return this.$message({
                    message: '小主，请您先选择 EXCEL 文件！',
                    type: 'warning',
                    showClose: true
                });
            }
            /* let oldData = JSON.parse(window.localStorage.getItem('excel') || '[]'),
                newData = [...oldData, ...this.tempData];
            window.localStorage.setItem('excel', JSON.stringify(newData)); */

            // 不可点击
            this.disabled = true;

            const complete = () => {
                this.$message({
                    message: '小主，奴家已经帮你把数据传完了！',
                    type: 'success',
                    showClose: true
                });
                this.show = false;
                this.disabled = false;
            };

            // 把数据一条条传给服务器
            let n = 0;
            const send = async () => {
                if (n > this.tempData.length - 1) {
                    complete();
                    return;
                }
                let body = this.tempData[n];
                let result = await createAPI(body);
                if (parseInt(result.code) === 0) {
                    n++;
                }
                send();
            };
            send();
        }
    }
};
</script>

<style lang="less" scoped>
.homeBox {
    position: fixed;
    top: 10px;
    right: 20px;
    z-index: 9999;
    font-size: 40px;
}

.buttonBox {
    padding: 15px;
    display: flex;
    width: 35%;
    justify-content: flex-start;
    & .el-button {
        margin-right: 20px !important;
    }
}

.tableBox {
    padding: 0 15px;
    h3 {
        font-size: 18px;
        color: #f56c6c;
        padding-bottom: 15px;
    }
}
</style>
